package block

import (
	"WeiXinCode/区块链学习/01_day_hdv2/utils"
	"bytes"
	"crypto/elliptic"
	"encoding/gob"
	"fmt"
	"io/ioutil"
)

type Wallets struct {
	WalletsMap map[string]*WalletKeyPair
}

//创建walltes，返回wallets实例
func NewWallets() *Wallets {
	var ws Wallets
	ws.WalletsMap = make(map[string]*WalletKeyPair)
	//1.把所有的钱包从{本地加载}出来
	if !ws.LoadFromFile() {
		fmt.Println("加载钱包数据失败！")
	}
	ws.LoadFromFile()
	//2返回实例
	return &ws
}

const WalletName = "wallet.dat"
func (ws *Wallets) CreateWallet() string {
	//调用newWalletKeyPair
	wallet := NewWalletKeyPair() // 创建一个公钥私钥
	//将返回的WalletKeyPair添加到WalletsMap里面
	address := wallet.GetAddress()
	ws.WalletsMap[address] = wallet
	//保存到本地
	// TODO
	res:=ws.SaveToFile()
	if !res {
		fmt.Println("创建钱包失败！")
	}
	return address
}
//保存钱包到文件
func (ws *Wallets)SaveToFile() bool {
	var buffer bytes.Buffer
	//将接口文件明确注册一下
	gob.Register(elliptic.P256())
	encoder:=gob.NewEncoder(&buffer)

	err:=encoder.Encode(ws)

	if err!=nil {
		fmt.Println("钱包序列化失败！,",err)
		return false
	}

	content:=buffer.Bytes()

	err=ioutil.WriteFile(WalletName,content,0600)
	if err != nil {
		fmt.Println("钱包创建失败！")
		return false
	}
	return true
}
//读取之前的钱包内容
func (ws *Wallets) LoadFromFile() bool {
	if !utils.IsFileExist(WalletName) {
		fmt.Println("钱包不存在，准备创建钱包！")
		return true
	}
	//读取文件
	content,err:=ioutil.ReadFile(WalletName)
	if err != nil {
		fmt.Println("读取钱包失败！")
		return false
	}
	//gob解码
	gob.Register(elliptic.P256())
	decoder:=gob.NewDecoder(bytes.NewReader(content))
	var wallets Wallets
	err=decoder.Decode(&wallets)
	if err != nil {
		fmt.Println("解码钱包失败！")
		return false
	}
	//复制给ws
	ws.WalletsMap=wallets.WalletsMap
	return true
}
//打印钱包内容
func (ws *Wallets)ListAddress() []string {
	//遍历ws.WalletsMap结构返回可以即可
	var addresses []string
	for address,_:=range ws.WalletsMap{
		addresses=append(addresses,address)
	}
	return addresses
}